package org.zcl.rocketmq.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import org.zcl.rocketmq.entity.Order;
import org.zcl.rocketmq.service.OrderService;

import java.util.Date;

/**
 * .
 *
 * @author zhuchenglin
 * @since 2024/6/22 13:13
 */
@Component
@Slf4j
@RocketMQTransactionListener
public class TransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private OrderService orderService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        Order order = (Order) o;
        try {
            orderService.addOrder(order);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String key = message.getHeaders().get("key").toString();
        log.info("回查订单id：{},回查时间：{}", key, new Date());
        Order order = orderService.getById(key);
        if (order == null) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        long l = new Date().getTime() - order.getCreateTime().getTime();
        long time = l / (60 * 1000);
        if (time > 1) {
            orderService.removeById(key);
            log.info("删除订单：{}", key);
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        Integer status = order.getStatus();
        if (status == 1) {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }
}
